package com.biubiux2.client;

import com.biubiux2.codec.MessageEncryptAndDecryptHandler;
import com.biubiux2.codec.MessageProtocolCodec;
import com.biubiux2.codec.compress.MessageCompressHandler;
import com.biubiux2.handler.ClientEncryptHandler;
import com.biubiux2.handler.HeartBeatClientHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @author noexcs
 * @since 8/10/2022 2:15 PM
 */
public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {

    private ChannelPipeline pipeline;

    private ArrayList<ChannelHandler> channelHandlers = new ArrayList<>();

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        pipeline = ch.pipeline();
        pipeline.addLast(new LengthFieldBasedFrameDecoder(10240, 0, 4, 0, 0));
        pipeline.addLast(new MessageProtocolCodec());
        pipeline.addLast(new IdleStateHandler(60, 50, 60, TimeUnit.SECONDS));
        pipeline.addLast(new HeartBeatClientHandler());
        pipeline.addLast(new MessageCompressHandler());
        pipeline.addLast(new ClientEncryptHandler());
        for (ChannelHandler channelHandler : channelHandlers) {
            pipeline.addLast(channelHandler);
        }
    }

    public void addExtraChannelHandler(ChannelHandler... handlers) {
        for (ChannelHandler handler : handlers) {
            channelHandlers.add(handler);
        }
    }

}
